<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';

import { computed, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

import { AuthenticationForgetPassword, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { initiatePasswordResetApi } from '#/api/core/auth';

defineOptions({ name: 'ForgetPassword' });

const router = useRouter();
const loading = ref(false);

// ResetType枚举值
// 根据Terra.Core.Common.Enums.Identity.ResetType枚举定义
enum ResetType {
  Email = 1, // 邮件方式
  SMS = 2    // 短信方式
}

// 表单定义 - 只保留邮箱输入框
const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: 'example@example.com',
      },
      fieldName: 'email',
      label: $t('authentication.email'),
      rules: z
        .string()
        .min(1, { message: $t('authentication.emailRequired') })
        .email({ message: $t('authentication.emailValidErrorTip') }),
    },
  ];
});

/**
 * 处理表单提交
 * @param values 表单值
 */
async function handleSubmit(values: Recordable<any>) {
  try {
    loading.value = true;

    // 调用密码重置接口 - 使用枚举值
    const { data: _ } = await initiatePasswordResetApi({
      account: values.email,     // 使用email字段作为account值
      resetType: ResetType.Email // 使用枚举值而不是字符串
    });

    // 请求成功
    ElMessage.success($t('authentication.resetLinkSent'));

    // 重定向回登录页
    setTimeout(() => {
      router.push('/auth/login');
    }, 2000);

  } catch (error: any) {
    // 请求失败处理
    const message = error.response?.data?.message || $t('authentication.resetFailed');
    ElMessage.error(message);
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <AuthenticationForgetPassword
    :form-schema="formSchema"
    :loading="loading"
    @submit="handleSubmit"
  />
</template>
